package com.dy.队列.顺序队列.循环队列;

import com.dy.队列.IQueue;

public class CircleSqQueue implements IQueue {
    private Object[] queueElem;
    private int front;
    private int rear;

    @Override
    public void clear() {
        front = 0;
        rear = 0;
    }

    public boolean isFull(){
        return (rear+1)%queueElem.length ==front;
    }

    @Override
    public boolean isEmpty() {
        return rear == front;
    }

    @Override
    public int length() {
        return (rear - front + queueElem.length) % queueElem.length;
    }

    @Override
    public Object peek() {
        if(front==rear){
            return null;
        }
        return queueElem[front];
    }

    @Override
    public void offer(Object x) throws Exception {
        if(((rear+1)%queueElem.length)==front){
            throw new  Exception("队列已满");

        }
        else{
            queueElem[rear] = x;
            rear = (rear+1)%queueElem.length;
        }
    }

    @Override
    public Object poll() {
        if(front==rear){
            return null;
        }
        else{
            Object t = queueElem[front];
            front = (front+1)%queueElem.length;
            return t;
        }

    }

    public void display(){
        if(!isEmpty()){
            for(int i=front;i!=rear; i=(i+1)%queueElem.length){
                System.out.print(queueElem[i].toString()+" ");
            }
        }
        else System.out.println("此队列为空");
    }
}
